package com.webcat.redis.service;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.util.Calendar;
import java.util.Date;

public class RedisDaySeqService {


    private RedisService redisService;

    private RedisConnectionFactory redisConnectionFactory;

    public RedisDaySeqService(RedisService redisService, RedisConnectionFactory redisConnectionFactory) {
        this.redisService = redisService;
        this.redisConnectionFactory = redisConnectionFactory;
    }

    public long generateSeq(String key) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisConnectionFactory);
        long counter = entityIdCounter.incrementAndGet();
        if ((counter == 1)) {// 初始设置过期时间
            redisService.expire(key, diffZeroDate(new Date()));
        }
        return counter;
    }

    public long generateSeq(String key, long initValue) {
        return generateSeq(key) + initValue;
    }

    /**
     * 当前时间与23:59:59的差值
     * @param date
     * @return
     */
    private static long diffZeroDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        Date zeroDate = getZeroDate();
        calendar.setTime(zeroDate);
        long zero = calendar.getTimeInMillis()/1000;

        calendar.setTime(date);
        long cur = calendar.getTimeInMillis()/1000;

        return zero - cur;

    }

    /**
     * 生成当天23:59:59日期
     * @return
     */
    private static Date getZeroDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }
}
